//
//  GetSecretViewController.m
//  QRMaster
//
//  Created by myApple on 15/12/2.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "GetSecretViewController.h"
#import "RequestNetWork.h"
#import "PromptInfoView.h"
#import "validateInputValue.h"
#import "openssl/rsa.h"
#import "CRSA.h"

@interface GetSecretViewController ()<UITextFieldDelegate>
{
    UILabel * titleLabel;
    UITextField * telePhoneField;
    UITextField * checkTextField;
    UIButton * checkBtn;
    NSTimer * time;
    CRSA * rsa;
    UIButton * nextBtn;
}

@end

static int count = 0;

@implementation GetSecretViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
//    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    self.title = NSLocalizedString(@"getOriginKey", nil);
    [self prepareView];
    rsa = [CRSA shareInstance];
    // Do any additional setup after loading the view.
}


-(void)prepareView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    //    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 16;
    float y = 16;
    float width = ScreenWidth * 0.6;
    float height = 40;
    
    checkTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    
    checkTextField.placeholder = NSLocalizedString(@"checkNum", nil);
    checkTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 0)];
    checkTextField.leftViewMode = UITextFieldViewModeAlways;
//    checkTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"checkNum", nil) attributes:@{NSForegroundColorAttributeName:UIColorFromRGB(0x727272)}];
    checkTextField.font = [UIFont systemFontOfSize:18.0];
    checkTextField.borderStyle = UITextBorderStyleNone;
    checkTextField.backgroundColor = [UIColor whiteColor];
    checkTextField.layer.borderWidth = 0.5;
    checkTextField.layer.borderColor = [[UIColor colorWithRed:0.6788 green:0.6788 blue:0.6788 alpha:1.0] CGColor];
    checkTextField.keyboardType = UIKeyboardTypeNumberPad;
    checkTextField.delegate = self;
    checkTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:checkTextField];
    
    x += width + 10;
    width = ScreenWidth - width - 42;
    checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame = CGRectMake(x, y, width, height);
    [checkBtn setTitle: NSLocalizedString(@"getCheckNum", nil) forState:0];
    [checkBtn setTitleColor:[UIColor whiteColor] forState:0];
    checkBtn.titleLabel.font = [UIFont systemFontOfSize:16.0];
    [checkBtn setBackgroundColor:UIColorFromRGB(0x7dc234)];
    checkBtn.layer.cornerRadius = 5.0;
    checkBtn.layer.masksToBounds = YES;
    checkBtn.userInteractionEnabled = YES;
    [checkBtn addTarget:self action:@selector(getData) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkBtn];
    
    x = 16;
    y += height + 26;
    width = ScreenWidth - 32;
    height = 48;
    nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, width, height)];
    [nextBtn setTitleColor:[UIColor whiteColor] forState:0];
    [nextBtn setTitle:NSLocalizedString(@"getOriginKey", nil) forState:0];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:19.0];
    nextBtn.layer.cornerRadius = 5.0;
    nextBtn.layer.masksToBounds = YES;
    [nextBtn setBackgroundColor:UIColorFromRGB(0xc1c1c1)];
    nextBtn.userInteractionEnabled = NO;
    [nextBtn addTarget:self action:@selector(MakeSure) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:nextBtn];
    
    UITapGestureRecognizer * removeKeyBoardTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard)];
    [self.view addGestureRecognizer:removeKeyBoardTap];
}

#pragma mark - 验证码输入监听
- (void)textFieldDidChange:(UITextField *)textField{
    if(textField.text.length != 0){
        nextBtn.enabled = YES;
        nextBtn.backgroundColor = UIColorFromRGB(0x7dc234);
        checkBtn.enabled = NO;
        checkBtn.backgroundColor = UIColorFromRGB(0xc1c1c1);
    }else{
        nextBtn.enabled = NO;
        nextBtn.backgroundColor = UIColorFromRGB(0xc1c1c1);
        checkBtn.enabled = YES;
        checkBtn.backgroundColor = UIColorFromRGB(0x7dc234);
    }
}


//验证码的网络请求
-(void)getData
{
 
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(GETMODIFYVCODE) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            [nextBtn setBackgroundColor:UIColorFromRGB(0x7dc234)];
            nextBtn.userInteractionEnabled = YES;
            [PromptInfoView showMessage:NSLocalizedString(@"getCheckNumPromt", nil)];
             time = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];

            [time fire];
        }
        else if ([[error objectForKey:@"status"]integerValue] == 165) {
            
            [PromptInfoView showMessage:NSLocalizedString(@"accountNoRegist", nil) superView:self.view];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }
    }];
}


//获取密钥
-(void)MakeSure
{
    if (checkTextField.text.length == 0) {
        [PromptInfoView showMessage:NSLocalizedString(@"vcodeWrong", nil)];
        return;
    }
    [checkTextField resignFirstResponder];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    [postDict setValue:checkTextField.text forKey:@"code"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    __block GetSecretViewController * weakSelf = self;
    [self startWaiting:nil color:nil addToView:self.view];
    [rnk initWithPath:POST(GETOLDPWD) params:postDict block:^(id downLoadData, id error) {
        [weakSelf stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            NSString * oldPwd = [rsa decryptByRsa:[[downLoadData objectForKey:@"data"] objectForKey:@"password"] withKeyType:KeyTypePrivate];
            if (weakSelf.oldPassWord) {
                weakSelf.oldPassWord(oldPwd);
            }
            [weakSelf BackClick];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"] superView:self.view];
        }

    }];
}


//启动定时器
-(void)updateTime
{
    count ++;
    if (count >= 60) {
        if ([time isValid]) {
            [time invalidate];
            time = nil;
            count = 0;
        }
        [checkBtn setTitle:NSLocalizedString(@"getCheckNum", nil) forState:0];
        checkBtn.userInteractionEnabled = YES;
        checkBtn.backgroundColor = UIColorFromRGB(0x7dc234);
        nextBtn.userInteractionEnabled = NO;
        nextBtn.backgroundColor = UIColorFromRGB(0xc1c1c1);
        return;
    }
    else
    {
        checkBtn.userInteractionEnabled = NO;
        checkBtn.backgroundColor = UIColorFromRGB(0xc1c1c1);
        nextBtn.userInteractionEnabled = YES;
        nextBtn.backgroundColor = UIColorFromRGB(0x7dc234);
    }
    NSString * fisrtString = NSLocalizedString(@"timePromt", nil) ;
    NSString * lastString = NSLocalizedString(@"timePromtLast", nil);
    [checkBtn setTitle:[NSString stringWithFormat:@"%@%d%@",fisrtString,(60 - count),lastString] forState:0];
}

#pragma mark -- uitextFiledDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self hiddenKeyboard];
    return YES;
}

//-(void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    [time setFireDate:[NSDate distantFuture]];
//    count = 0;
//}

-(void)hiddenKeyboard
{
    [telePhoneField resignFirstResponder];
    [checkTextField resignFirstResponder];
}

-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KCHiddenKeyBoardNotification" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
